<script setup lang="ts">
import { fetchProjectDetailAPI } from '@/apis/fetchProjectDetail'
import { fetchProjectPersonnelListAPI } from '@/apis/fetchProjectPersonnelList'
import { removeTeammateAPI } from '@/apis/removeTeammate'
import router from '@/router'
import { useUserInfoStore } from '@/store/userInfo'

const userInfoStore = useUserInfoStore()

const projectId = ref('')
const project = ref<Project | undefined>()
const personList = ref<(Person | Staff)[]>([])

const loading = ref(true)

onLoad(async (options) => {
  if (options && options.project_id)
    projectId.value = options.project_id
})
onShow(() => loadData())

async function loadData() {
  if (!project.value) {
    const res = await fetchProjectDetailAPI(projectId.value, userInfoStore.userInfo!.token!)
    project.value = res.data?.data
  }

  // 地区经理 Part
  if (userInfoStore.belongTo(['1'])) {
    try {
      const res = await fetchProjectDetailAPI(project.value!.id!.toString(), userInfoStore.userInfo!.token!)
      project.value = res.data?.data as Project
      loading.value = false
      if (res.data?.data.foreman)
        personList.value = [res.data?.data.foreman]
    }
    catch (err) {
      loading.value = false
      uni.showToast({ title: '获取数据失败', icon: 'none' })
    }
  }
  // 工长 Part
  else if (userInfoStore.belongTo(['2'])) {
    try {
      const res = await fetchProjectPersonnelListAPI(project.value!.id!.toString(), userInfoStore.userInfo!.token!)
      personList.value = (res.data as any).data as Person[]
      loading.value = false
    }
    catch (err) {
      loading.value = false
      uni.showToast({ title: '获取数据失败', icon: 'none' })
    }
  }
}

/* ------------------------------ 工长 Part START ----------------------------- */
const swipeActions = [
  {
    name: '移出',
    action: 'delete',
    style: { bgColor: '#FF2636' },
  },
]
/* ------------------------------- 工长 Part END ------------------------------ */

/* ------------------------------- 事件处理 START ------------------------------- */
function handleCallContact(phoneNumber?: string) {
  if (phoneNumber) {
    uni.makePhoneCall({
      phoneNumber,
      success: () => {},
      fail: () => { uni.showToast({ title: '呼叫取消', icon: 'none' }) },
    })
  }
}

function handleAssign() {
  if (project.value?.id) {
    // 如果是工长，分配员工
    if (userInfoStore.belongTo(['2'])) {
      router.push({
        name: 'assignTeammates',
        params: {
          project_id: project.value.id.toString(),
        },
      })
    }
    // 如果是地区经理，分配工长
    else if (userInfoStore.belongTo(['1'])) {
      router.push({
        name: 'assignForeman',
        params: {
          project_id: project.value.id.toString(),
          is_initial: 'false',
        },
      })
    }
  }
  else {
    uni.showToast({ title: '发生错误', icon: 'none' })
  }
}
/* -------------------------------- 事件处理 END -------------------------------- */

/* ------------------------------ 工长事件处理 START ------------------------------ */
async function handleSwipeAction(id: string, e: any) {
  if (e.item.action === 'delete') {
    const res = await removeTeammateAPI(id, userInfoStore.userInfo!.token!)
    if (res.data?.code === 1) {
      personList.value = personList.value.filter((person) => {
        return (person as Person).id.toString() !== id.toString()
      })
    }
    else { uni.showToast({ title: res.data?.msg, icon: 'none' }) }
  }
  else {
    uni.showToast({ title: '移出失败，请稍后重试', icon: 'none' })
  }
}
/* ------------------------------- 工长事件处理 END ------------------------------- */
</script>

<template>
  <Spacer height="30" />
  <ContactCard
    :contact-name="project?.contacts_name || '未知'" contact-identity="业主"
    :contact-mobile="project?.contacts_mobile || '未知'" @call="handleCallContact(project?.contacts_mobile)"
  />
  <Spacer height="30" />
  <view v-if="personList.length > 0" class="rounded-20rpx overflow-hidden">
    <view v-for="person in personList" :key="(person as Person).id">
      <NextSwipeAction v-if="userInfoStore.belongTo(['2'])" :btn-group="swipeActions" @btn-click="(e: Event) => handleSwipeAction(`${(person as Person).id}`, e)">
        <PersonItemWithCallButton
          :avatar="person.avatar || 'http://jzt.tykhrs.cn/uploads/20240204/87b5977293b9856b96b77b21dcfc3e2a.png'"
          :name="(person as Person).name || '未知'"
          :identity="(person as Person).profession || '未知'"
          :phone-number="person.mobile || '未知'"
          @call="() => handleCallContact(person.mobile)"
        />
      </NextSwipeAction>
      <PersonItemWithCallButton
        v-else
        :avatar="person.avatar || 'http://jzt.tykhrs.cn/uploads/20240204/87b5977293b9856b96b77b21dcfc3e2a.png'"
        :name="(person as Staff).nickname || '未知'"
        identity="工长"
        :phone-number="person.mobile || '未知'"
        @call="handleCallContact(person.mobile)"
      />
      <Divider />
    </view>
  </view>
  <PageDefault v-else />
  <Spacer height="120" />
  <uv-loading-page :loading="loading" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
  <Spacer height="240" />
  <RGButton class="fixed bottom-80rpx x-center" @tap="handleAssign">
    分配人员
  </RGButton>
</template>

<route lang="yaml">
name: 'teammates'
style:
  navigationBarTitleText: '设置团队人员'
</route>
